<template>
	<view class="content">
		<g-watermark />
		<view class="content_form">
			<u-form :model="formData" ref="form" :label-width="120" label-align="left">
				<u-form-item label="收件人" prop="to" required>
					<view style="width: 100%;">
						<uni-easyinput v-model="formData.to" placeholder="请填写收件人"></uni-easyinput>
						<text @click="handleCS"
							style="color:#0960bd;margin-left: 20rpx;">{{ iscs ? '删除抄送' : '添加抄送' }}</text>
						<text @click="handleRecentlyEmail('to')" style="color:#0960bd;margin-left: 20rpx;">常用联系人</text>
					</view>
				</u-form-item>
				<u-form-item label="抄送" v-if="iscs">
					<view style="width: 100%;">
						<uni-easyinput v-model="formData.cc" placeholder="请填写抄送"></uni-easyinput>
						<view @click="handleRecentlyEmail('cc')" style="color:#0960bd;margin-left: 20rpx;">常用联系人</view>
					</view>
				</u-form-item>
				<u-form-item label="主题" prop="subject" required>
					<uni-easyinput v-model="formData.subject" placeholder="请填写主题"></uni-easyinput>
				</u-form-item>
				<LEditor v-model="formData.content" ref="lEditorRef" :excludeKeys="[]" uploadUrl="/email/upload"/>
				<u-form-item label="附件">
					<FileUpload ref="fileUploadRef" :msgId="formData.id" type="externalEmail" />
				</u-form-item>
				<template v-if="ishj">
					<u-form-item label="发送时间" prop="send_now" required>
						<u-radio-group v-model="formData.send_now" style="width: 100%;">
							<u-radio :name="'yes'" :wrap="true">
								立即发送
							</u-radio>
							<u-radio :name="'no'" :wrap="true">
								<view style="display: flex;gap:10rpx;align-items: center;">
									定时发送 <u-input disabled v-model="formData.send_time" placeholder="请选择时间" />
									<u-icon name="arrow-down" @click="showTime=true"></u-icon>
								</view>
							</u-radio>
						</u-radio-group>
					</u-form-item>
					<u-form-item label="回执" prop="receipt_state" required>
						<u-radio-group v-model="formData.receipt_state">
							<u-radio v-for="(item, index) in receipt_stateList" :key="index" :name="item.value">
								{{item.label}}
							</u-radio>
						</u-radio-group>
					</u-form-item>
					<u-form-item label="等级" prop="msg_level" required>
						<u-radio-group v-model="formData.msg_level">
							<u-radio v-for="(item, index) in msg_levelList" :key="index" :name="item.value">
								{{item.label}}
							</u-radio>
						</u-radio-group>
					</u-form-item>
				</template>
			</u-form>
		</view>

		<view class="body_bottom">
			<template v-if="type == 'reply'">
				<view type="primary" @click="handleSend('reply')">发送</view>
				<!-- <view @click="handleResetWrite()">重写</view> -->
			</template>
			<template v-else>
				<view type="primary" @click="handleSend('send')">发送</view>
				<view @click="handleSend('draft')">保存草稿</view>
				<view @click="handleShowMore">高级功能</view>
			</template>
		</view>
		<MxDatepicker format="yyyy-mm-dd hh:ii" type="datetime" :show="showTime" :value="times" :show-tips="true"
			:show-seconds="false" @confirm="handleConfirmTime" @cancel="showTime=false" />
		<TkiTree idKey="id" rangeKey="emailAddr" :range="recentlyEmailList" ref="recentlyEmailListRef"
			@confirm="handleRecentlyEmailListConfirm" :multiple="true" />
	</view>
</template>

<script>
	import {
		postFormAction,
	} from '@/utils/request.js';
	import {
		msg_levelList,
		receipt_stateList,
	} from './writebox.js'
	import MxDatepicker from '../../component/mx-datepicker/mx-datepicker'
	import SelectUser from '@/components/selectUser/index.vue'
	import FileUpload from '../../component/file-upload/file-upload.vue'
	import LEditor from '../../component/l-editor/l-editor.vue'
	import TkiTree from '@/components/tki-tree/tki-tree.vue'
	import moment from 'moment'
	import {
		replaceHtml
	} from '../common/tools.js'
	import {
		mapState
	} from "vuex";
	export default {
		components: {
			MxDatepicker,
			SelectUser,
			FileUpload,
			LEditor,
			TkiTree
		},
		data() {
			const that = this
			return {
				msg_levelList,
				receipt_stateList,
				formData: {
					to: "",
					cc: "",
					subject: "",
					content: "",
				},
				rules: {
					to: [{
						required: true,
						message: `收件人不能为空`,
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					subject: [{
						required: true,
						message: '主题不能为空',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					// content: [{
					// 	required: true,
					// 	message: '正文不能为空',
					// 	// 可以单个或者同时写两个触发验证方式 
					// 	trigger: ['change', 'blur'],
					// }],
				},
				url: {
					sendMsg: '/email/send',
					saveDraft: '/email/updateDraft',
					reply: '/email/reply',
					showMail: '/email/showMail',
					listRecentlyEmail: '/email/listRecentlyEmail'
				},
				ishj: false, //是否高级功能
				iscs: false, //抄送
				isms: false, //密送
				times: null,
				type: '',
				mainId: '',
				showTime: false,
				departmentList: [], //部门树
				currentModel: {}, //通过showMail取到的当前数据
				recentlyEmailList: [], //常用联系人
				recentlyEmailKey: '', //打开的key


			}
		},
		onLoad(options) {
			this.type = options.type || ''
			this.mainId = options.mainId || ''
			// this.getDepartmentsData()
			this.init()
			this.getEmailListRecentlyEmailData()
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.form.setRules(this.rules);
		},
		computed: {
			...mapState(["emailInfo", "loginInfo"]),
		},
		methods: {
			moment,
			init() {
				this.$nextTick(async () => {
					console.log("emailInfo", this.emailInfo)
					console.log("type", this.type)
					this.$refs.form.resetFields()
					this.formData = {
						send_now: 'yes',
						send_time: '',
						sendDate: '',
						to: '',
						cc: '',
						bcc: '',
						// isToOutBox: 'true',
						isSaveToSendBox: true,
						receipt_state: 0,
						msg_level: 0,
						id: -1,
						username: this.loginInfo.userName,
						email: this.emailInfo.email,
					}
					console.log("this.mainId", this.mainId)
					if (this.mainId) {
						const res = await postFormAction(this.url.showMail, {
							id: this.mainId,
							emailId: this.emailInfo.id
						})
						this.currentModel = res.data || {}
						this.currentModel.receipt_state = this.currentModel.receiptState;
						this.currentModel.msg_level = this.currentModel.msgLevel;
						if (this.currentModel.content) {
							this.currentModel.content = replaceHtml(this.currentModel
								.content) //this.currentModel.content.replaceAll('<', '&lt;')
							console.log("this.currentModel.content", this.currentModel.content)
						}
						if (this.currentModel.copyReceiver) {
							this.currentModel.cc = this.currentModel.copyReceiver
							this.iscs = true
						}
						if (this.currentModel.sendTime) {
							this.currentModel.send_now = 'no';
							this.currentModel.send_time = moment(this.currentModel.sendTime).format(
								'YYYY-MM-DD HH:mm');
						}
					}
					if (this.type == 'reply') {
						this.formData.subject = `回复：${this.currentModel.subject}`;
						this.formData.to = this.currentModel.sender;
						this.formData.content =
							`<p><br><br><br><br><br><br><br><p>------------------原始邮件------------------</p>${this.currentModel.content}</p>`;
						// this.formData.attachments = this.currentModel.attachments;
					} else if (this.type == 'draftbox' || this.type == 'outBox') {
						this.formData = {
							...this.formData,
							...this.currentModel,
							to: this.currentModel.receiver,
						};
					} else if (this.type == 'transmit' || this.type == 'outBox') {
						// const res = await postFormAction(this.url.showMail, {
						// 	id: this.mainId,
						// 	emailId: this.emailInfo.id
						// })
						// this.currentModel = res.data || {}
						this.formData = {
							...this.formData,
							...this.currentModel,
							to: '',
						}
						this.formData.subject = `Fw：${this.currentModel.subject}`;
						this.formData.content =
							`<br><br><br><br><br><br><br><p>------------------转发邮件信息------------------</p>` +
							this.currentModel.content;
					}
					if (this.formData.attachments && this.formData.attachments.length) {
						this.$refs.fileUploadRef.fileList = this.formData.attachments
					}
					console.log("this.formData", this.formData)
				});
			},
			//高级功能
			handleShowMore() {
				this.ishj = !this.ishj;
			},
			handleCS() {
				this.iscs = !this.iscs;
				if (!this.iscs) {
					this.formData.cc = '';
				}
			},


			//回调时间
			handleConfirmTime(e) {
				console.log("handleConfirmTime", e)
				const {
					value
				} = e
				this.formData.send_time = value
				this.showTime = false
			},
			handleReturn() {
				var pages = getCurrentPages();
				// var currPage = pages[pages.length - 1]; //当前页面
				var prevPage = pages[pages.length - 2]; //上一个页面
				prevPage.isDoRefresh = true
				uni.navigateBack()
			},
			//重写
			handleResetWrite() {
				this.init()
			},

			//常用联系人
			async getEmailListRecentlyEmailData() {
				const res = await postFormAction(this.url.listRecentlyEmail, {
					emailId: this.emailInfo.id
				})
				this.recentlyEmailList = res.data || [];
			},
			//打开常用联系人
			handleRecentlyEmail(key) {
				this.recentlyEmailKey = key
				this.$refs.recentlyEmailListRef._show()
			},
			//选择常用联系人回调
			handleRecentlyEmailListConfirm(e) {
				console.log('handleRecentlyEmailListConfirm', e)
				if (e && e.length) {
					this.formData[this.recentlyEmailKey] = e.map(item => item.emailAddr).join(',')
				}
				this.$forceUpdate()
			},
			//确定
			handleSend(type) {
				console.log("this.formData", this.formData)
				this.$refs.form.validate(async valid => {
					if (valid) {
						console.log('验证通过');
						try {
							this.formData.content = this.$refs.lEditorRef.content
							if (!this.formData.content) {
								uni.showToast({
									title: '请输入正文',
									icon: 'none'
								})
								return
							}
							const data = Object.assign({}, this.formData);
							data.emailId = this.emailInfo.id;
							data.sendDate = moment().format('YYYY-MM-DD');
							delete data.att
							const fileList = this.$refs.fileUploadRef.fileList
							console.log('fileList', fileList);
							// const files = []
							if (fileList && fileList.length) {
								data.attachments = fileList.map(item => item.id).join(',')
							}
							console.log('data', data);
							uni.showLoading({
								title: '加载中',
								mask: true
							});
							const afterUrl = `?emailId=${data.emailId}`
							let res = {}
							if (type == 'send') {
								res = await postFormAction(this.url.sendMsg + afterUrl, data);
							} else if (type == 'draft') {
								res = await postFormAction(this.url.saveDraft + afterUrl, data);
							} else if (type == 'reply') {
								res = await postFormAction(this.url.reply + afterUrl, data);
							}

							if (res.code == 200) {
								uni.showToast({
									title: '操作成功',
									icon: 'none'
								})
								this.handleReturn();
							} else {
								uni.showToast({
									title: res.msg,
									icon: 'none'
								})
							}
						} catch (error) {
							console.log('handleSend', error);
						} finally {
							uni.hideLoading()
						}
					} else {
						console.log('验证失败');
					}
				});

			}
		}
	}
</script>

<style lang="less" scoped>
	.content {
		overflow-y: auto;

		&_form {
			padding: 20rpx 20rpx 0;
			margin-bottom: 800rpx;
		}
	}

	.body_bottom {
		position: fixed;
		z-index: 10;
		bottom: 0;
		height: 100rpx;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-around;
		gap: 20rpx;
		background: #FFFFFF;
		box-shadow: 0rpx -2rpx 16rpx 0rpx rgba(0, 0, 0, 0.1);
	}
</style>